package com.team5.reptiles;

import com.team5.entity.NewStocks;
import com.team5.entity.RFRange;
import com.team5.mapper.NewStocksMapper;
import com.team5.mapper.RFRangeMapper;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class NewStockListingCalendar {
    @Autowired
    NewStocksMapper newStocksMapper;
    private static final Logger logger = Logger.getLogger(NewStockListingCalendar.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 0/10 * * * ?") // 每30分钟执行一次
    public void fetchNewStockListingData() {
        newStocksMapper.deleteAll();//清除数据
        int logId = LogIdGenerator.getNextLogId(); // 获取日志ID
        long startTime = System.currentTimeMillis(); // 记录爬虫开始时间

        // Set ChromeDriver path
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\86155\\Desktop\\chrome-win64\\chromedriver.exe");

        // Configure ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless"); // Enable headless mode
        options.addArguments("--disable-gpu"); // Applicable to Windows OS
        options.addArguments("--no-sandbox");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver(options);

        try {
            // Define URL to scrape
            String url = "https://vip.stock.finance.sina.com.cn/corp/go.php/vRPD_NewStockIssue/page/1.phtml";
            driver.get(url);

            // Wait for the page to load
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

            // Get the page source
            String pageSource = driver.getPageSource();

            // Parse HTML using Jsoup
            Document doc = Jsoup.parse(pageSource);

            // Find all <tr> elements
            Elements trs = doc.select("tr");

            // Skip the first <tr> element
            boolean first = true;

            // Iterate through each <tr> element, looking for security name and listing date information
            for (Element tr : trs) {
                if (first) {
                    first = false;
                    continue; // Skip the first <tr> element
                }
                Elements tds = tr.select("td");
                // Check if the number of child elements is sufficient
                if (tds.size() >= 4) {
                    String securityName = tds.get(2).text().trim(); // Security name
                    String listingDateString = tds.get(4).text().trim(); // Listing date
                    // Skip the current data if listing date is empty or equals "上市日期"
                    if (!listingDateString.isEmpty() && !listingDateString.equals("上市日期")) {
                        try {
                            // Parse the date string into a date object
                            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                            Date listingDate = format.parse(listingDateString);
                            // Get the current date
                            Date today = new Date();
                            // Calculate six months ago date
                            long sixMonthsAgo = today.getTime() - (30 * 24 * 60 * 60 * 1000L * 6); // 180 days
                            Date sixMonthsAgoDate = new Date(sixMonthsAgo);
                            // Check if the listing date is within the last six months
                            if (listingDate.after(sixMonthsAgoDate)) {
                                NewStocks newStocks=new NewStocks();
                                newStocks.setName(securityName);
                                newStocks.setSSDate(listingDate);
                                newStocksMapper.insert(newStocks);
                            }
                        } catch (java.text.ParseException e) {
                            // Handle date parsing exception
                            System.out.println("日期解析错误：" + listingDateString);
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Error fetching new stock listing data: " + e.getMessage());
        } finally {
            // Close WebDriver
            if (driver != null) {
                driver.quit();
            }
        }

        long endTime = System.currentTimeMillis(); // Record crawler end time

        // Log crawler end information
        String logMessageEnd = "日志ID: " + logId +
                "，爬虫行为说明: 抓取新股上市日历数据" +
                ", 爬虫网址: https://vip.stock.finance.sina.com.cn/corp/go.php/vRPD_NewStockIssue/page/1.phtml"+
                "，爬虫开始时间: " + dateFormat.format(new Date(startTime)) +
                "，爬虫结束时间: " + dateFormat.format(new Date(endTime)) +
                "，爬虫数据表: 新股上市日历";
        logger.info(logMessageEnd);
    }
}
